package com.sumainfor.wx.system.epc.service;

import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.ListMapMergeUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.wx.system.annotation.DS;
import com.sumainfor.wx.system.epc.dao.OrderMapper;
import com.sumainfor.wx.system.epc.dao.RepairMapper;
import com.sumainfor.wx.system.feign.MarketFeign.MarketFeign;
import com.sumainfor.wx.system.feign.TenantFeign.TenantFeign;
import com.sumainfor.wx.system.feign.ZuulFeign.ZuulFeign;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述:
 *
 * @Auther: zhlu
 * @Date: 2019/6/11 19:20
 * @Description:
 */
@Service
@Log4j2
public class OrderService {

    @Autowired
    OrderMapper OrderMapper;

    @Autowired
    ZuulFeign ZuulFeign;

    @Autowired
    MarketFeign MarketFeign;

    @Autowired
    TenantFeign TenantFeign;

    @Autowired
    RepairMapper RepairMapper;

    /**
     * 功能描述:
     * 根据unionid获取当前用户的工单总数（包括强派工单）
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/6/11 19:47
     */
    public JsonResult getOrderCount(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<String, Object>();
        Integer getOrderCoerceCount = OrderMapper.getOrderCoerceCount(new HashMap<String, Object>() {{
            put("SysUserId",ContextUtils.getUserId());
        }});
        if (getOrderCoerceCount > 0) {
            result.put("CoerceCount", getOrderCoerceCount);
        } else {
            result.put("CoerceCount", 0);
        }
        Integer getOrderCount = OrderMapper.getOrderCount(new HashMap<String, Object>() {{
            put("SysUserId",ContextUtils.getUserId());
        }});
        if (getOrderCount > 0) {
            result.put("OrderCount", getOrderCount);
        } else {
            result.put("OrderCount", 0);
        }

        return JsonResult.success(result);
    }

    /**
     * 功能描述:
     * 根据用户编号查询我的工单列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/6/12 16:46
     */
    public List<Map<String, Object>> getMyOrderList(Map<String, Object> params) {
        params.put("SysUserId", ContextUtils.getUserId());
        List<Map<String, Object>> getMyOrderList = OrderMapper.getMyOrderList(params);
        if (getMyOrderList.size() > 0) {
            //获取房源资料
            JsonResult jsonResult1 = MarketFeign.getAllHousingConLists();
            log.info("jsonResult1----" + jsonResult1);
            List<Map<String, Object>> AllHousingConLists = (List<Map<String, Object>>) jsonResult1.getResult();
            getMyOrderList = ListMapMergeUtil.ListMergeUtils(getMyOrderList, AllHousingConLists, "HouCon");

            //获取报修人
            for (Map<String, Object> map : getMyOrderList) {
                Integer RepType = Integer.valueOf(map.get("RepType").toString());
                List<String> ids = new ArrayList<String>();
                ids.add(map.get("RepairsId").toString());
                log.info("RepType-------" + RepType);
                switch (RepType) {
                    case 1://报修人为普通用户
                        //获取租客资料
                        List<Map<String, Object>> TenantInfoByIdList = TenantFeign.selectTenantInfoByIdList(ids);
                        log.info("TenantInfoByIdList-----------------" + TenantInfoByIdList);
                        if (TenantInfoByIdList.size() > 0) {
//                            map.putAll(TenantInfoByIdList.get(0));
                            map.put("RepName", TenantInfoByIdList.get(0).get("Realname"));
                        } else {
                            map.put("RepName", null);
                        }
                        break;
                    case 2://管家报修
                        JsonResult jsonResult3 = ZuulFeign.getUser(ids);
                        List<Map<String, Object>> UserList = (List<Map<String, Object>>) jsonResult3.getResult();
                        if (UserList.size() > 0) {
//                            map.putAll(UserList.get(0));
                            map.put("RepName", UserList.get(0).get("username"));
                        } else {
                            map.put("RepName", null);
                        }
                        break;
                }
            }
        }
        return getMyOrderList;
    }

    /**
     * 功能描述:
     * 根据用户编号查询我的工单列表总数
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/6/12 16:45
     */
    public Integer getMyOrderListCount(Map<String, Object> params) {
        params.put("SysUserId", ContextUtils.getUserId());
        return OrderMapper.getMyOrderListCount(params);
    }

    /**
     * 功能描述:
     * 受理工单池维修工单为我的工单
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/6/14 9:58
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult AcceptRepairMyOrder(Map<String, Object> params) {
        //是否存在当前订单
        Integer getDoesItExistRepair = RepairMapper.getDoesItExistRepair(params);
        if (getDoesItExistRepair <= 0) {
            return JsonResult.error("不存在当前维修工单！");
        }

        //判断是否已被接单
        if (!RepairMapper.getRepMainDataStateByRepId(MapUtils.getString(params, "RepId")).equals(1)) {
            return JsonResult.error("维修单已被接单");
        }

        try {
            //所有新增处理
            Map<String, Object> commonInsertParms = new HashMap<String, Object>();
            commonInsertParms.put("by", ContextUtils.getUserId());//操作人
            commonInsertParms.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonInsertParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(commonInsertParms);
            params.putAll(commonInsertParms);

            params.put("SysUserId", ContextUtils.getUserId());//接单人
            params.put("OrdTime", ConvertDateTime.getCurrentTime());//接时间
            //受理工单池维修工单为我的工单
            OrderMapper.AcceptRepairMyOrder(params);


            //修改处理
            Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
            commonUpdateParms.put("by", ContextUtils.getUserId());//操作人
            commonUpdateParms.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonUpdateParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(commonUpdateParms);
            params.putAll(commonUpdateParms);
            //受理成功之后，修改维修工单
            params.put("OrdState", 1);//工单状态   0无状态  1待维修   2已维修
            params.put("RepState", 2);//状态   1待接单   2已接单  3被强派
            RepairMapper.UpdateRepair(params);

            return JsonResult.success("受理成功，请及时跟进维修！");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return JsonResult.error("服务器繁忙，请稍后重试！");
        }

    }

}
